# 主循环内工具函数
from config import * 

# 虚拟棋盘 17*17，用于判断是否有玩家获胜
class Virtual_board:
    def __init__(self):
        self.board = [[-1 for j in range(17)] for i in range(17)]

    def win_judge(self,move:tuple,color:int): # move = (x,y)
        x, y = move
        # 检查水平方向
        count = 1  # 当前下子位置已经有一个棋子
        # 向左检查
        i = 1
        while y - i >= 0 and self.board[x][y - i] == color:
            count += 1
            i += 1
        # 向右检查
        i = 1
        while y + i < 17 and self.board[x][y + i] == color:
            count += 1
            i += 1
        if count >= 5:
            return True
        # 检查垂直方向
        count = 1
        # 向上检查
        i = 1
        while x - i >= 0 and self.board[x - i][y] == color:
            count += 1
            i += 1
        # 向下检查
        i = 1
        while x + i < 17 and self.board[x + i][y] == color:
            count += 1
            i += 1
        if count >= 5:
            return True
        # 检查左上到右下对角线
        count = 1
        # 向左上检查
        i = 1
        while x - i >= 0 and y - i >= 0 and self.board[x - i][y - i] == color:
            count += 1
            i += 1
        # 向右下检查
        i = 1
        while x + i < 17 and y + i < 17 and self.board[x + i][y + i] == color:
            count += 1
            i += 1
        if count >= 5:
            return True
        # 检查右上到左下对角线
        count = 1
        # 向右上检查
        i = 1
        while x - i >= 0 and y + i < 17 and self.board[x - i][y + i] == color:
            count += 1
            i += 1
        # 向左下检查
        i = 1
        while x + i < 17 and y - i >= 0 and self.board[x + i][y - i] == color:
            count += 1
            i += 1
        if count >= 5:
            return True
        return False

    def reset_board(self):
        self.board = [[-1 for j in range(17)] for i in range(17)]

def pos_judge(pos:tuple):
    # 计算最近的格子位置
    c_my_x,c_my_y = pos
    pos_re_x = -100
    pos_re_y = -100

    c_my_y -= START_Y
    c_my_x -= START_X
    if c_my_x > -15 and c_my_y > -15:
        pos_re_x = c_my_x % GRID_SIZE
        pos_re_y = c_my_y % GRID_SIZE
    if pos_re_x < 15 :
        c_my_x = c_my_x // GRID_SIZE
    elif pos_re_x > 22:
        c_my_x = c_my_x // GRID_SIZE+1
    if pos_re_y < 15:
        c_my_y = c_my_y // GRID_SIZE
    elif pos_re_y > 22:
        c_my_y = c_my_y // GRID_SIZE + 1
    return c_my_x,c_my_y

